//
//  AGHTTPManagement.m
//  VideoMark
//
//  Created by LiaoChenliang on 2021/12/17.
//  Copyright © 2021 DS. All rights reserved.
//

#import "AGHTTPManagement.h"

@implementation AGHTTPManagement
static AGHTTPManagement *__one;

+ (AGHTTPManagement *)shared {
static dispatch_once_t oneToken;
    dispatch_once(&oneToken, ^{
        __one = [[AGHTTPManagement alloc]init];

    });
    return __one;
}

+ (BOOL)isNetwork {
    return [PPNetworkHelper isNetwork];
}

+ (BOOL)isWWANNetwork {
    return [PPNetworkHelper isWWANNetwork];
}

+ (BOOL)isWiFiNetwork {
    return [PPNetworkHelper isWiFiNetwork];
}

+ (void)openLog {
    [PPNetworkHelper openLog];
}

+ (void)closeLog {
    [PPNetworkHelper closeLog];
}

+ (void)cancelAllRequest {
    [PPNetworkHelper cancelAllRequest];
}

+ (void)cancelRequestWithURL:(NSString *)URL {
    [PPNetworkHelper cancelRequestWithURL:URL];
}

+(void)networkStatusWithBlock:(PPNetworkStatus)networkStatus{
    [PPNetworkHelper networkStatusWithBlock:networkStatus];
}

#pragma mark - GET请求无缓存
+ (NSURLSessionTask *)GET:(NSString *)URL
               parameters:(id)parameters
                  success:(PPHttpRequestSuccess)success
                  failure:(PPHttpRequestFailed)failure {
    NSString *pathURL = [NSString stringWithFormat:@"%@%@",[AGHTTPManagement shared].baseUrl,URL];
    if ([self filterNetwork]){return nil;}
    return [PPNetworkHelper GET:pathURL headers:[self setupHeaders:URL] parameters:parameters responseCache:nil success:success failure:failure];
}

#pragma mark - POST请求无缓存
+ (NSURLSessionTask *)POST:(NSString *)URL
                parameters:(id)parameters
                   success:(PPHttpRequestSuccess)success
                   failure:(PPHttpRequestFailed)failure {
    NSString *pathURL = [NSString stringWithFormat:@"%@%@",[AGHTTPManagement shared].baseUrl,URL];
    if ([self filterNetwork]){return nil;}
    return [PPNetworkHelper POST:pathURL headers:[self setupHeaders:URL] parameters:parameters responseCache:nil success:success failure:failure];
}

#pragma mark - GET请求自动缓存
+ (NSURLSessionTask *)GET:(NSString *)URL
               parameters:(id)parameters
            responseCache:(PPHttpRequestCache)responseCache
                  success:(PPHttpRequestSuccess)success
                  failure:(PPHttpRequestFailed)failure {
    NSString *pathURL = [NSString stringWithFormat:@"%@%@",[AGHTTPManagement shared].baseUrl,URL];
    if ([self filterNetwork]){return nil;}
    return [PPNetworkHelper GET:pathURL headers:[self setupHeaders:URL] parameters:parameters responseCache:responseCache success:success failure:failure];
}

#pragma mark - POST请求自动缓存
+ (NSURLSessionTask *)POST:(NSString *)URL
                parameters:(id)parameters
             responseCache:(PPHttpRequestCache)responseCache
                   success:(PPHttpRequestSuccess)success
                   failure:(PPHttpRequestFailed)failure {
    NSString *pathURL = [NSString stringWithFormat:@"%@%@",[AGHTTPManagement shared].baseUrl,URL];
    if ([self filterNetwork]){return nil;}
    return [PPNetworkHelper POST:pathURL headers:[self setupHeaders:URL] parameters:parameters responseCache:responseCache success:success failure:failure];
}

#pragma mark - 上传文件
+ (NSURLSessionTask *)uploadFileWithURL:(NSString *)URL
                             parameters:(id)parameters
                                   name:(NSString *)name
                               filePath:(NSString *)filePath
                               progress:(PPHttpProgress)progress
                                success:(PPHttpRequestSuccess)success
                                failure:(PPHttpRequestFailed)failure {
    if ([self filterNetwork]){return nil;}
    return [PPNetworkHelper uploadFileWithURL:URL headers:[self setupHeaders:URL] parameters:parameters name:name filePath:filePath progress:progress success:success failure:failure];
}

#pragma mark - 上传多张图片
+ (NSURLSessionTask *)uploadImagesWithURL:(NSString *)URL
                               parameters:(id)parameters
                                     name:(NSString *)name
                                   images:(NSArray *)images
                                fileNames:(NSArray<NSString *> *)fileNames
                               imageScale:(CGFloat)imageScale
                                imageType:(NSString *)imageType
                                 progress:(PPHttpProgress)progress
                                  success:(PPHttpRequestSuccess)success
                                  failure:(PPHttpRequestFailed)failure {
    if ([self filterNetwork]){return nil;}
    return [PPNetworkHelper uploadImagesWithURL:URL headers:[self setupHeaders:URL] parameters:parameters name:name images:images fileNames:fileNames imageScale:imageScale imageType:imageType progress:progress success:success failure:failure];
}

#pragma mark - 下载文件
+ (NSURLSessionTask *)downloadWithURL:(NSString *)URL
                              fileDir:(NSString *)fileDir
                             progress:(PPHttpProgress)progress
                              success:(void(^)(NSString *))success
                              failure:(PPHttpRequestFailed)failure {
    if ([self filterNetwork]){return nil;}
    return [PPNetworkHelper downloadWithURL:URL fileDir:fileDir progress:progress success:success failure:failure];
}

+ (BOOL)filterNetwork{
    if([AGHTTPManagement shared].disable){
        NSLog(@"[AGHTTPManagement shared].disable = true");
        return true;
    }else{
        return false;
    }
}

+ (NSDictionary *)setupHeaders:(NSString *)url{
    NSInteger type = [AGHTTPManagement shared].type;
    switch (type) {
        case 0:
            return @{};
            break;
        case 1:
            return [self setupWebAPHeaders:url];
            break;
        case 2:
            return [self setupHMACHeaders:url];
            break;
        default:
            return @{};
            break;
    }
}


+ (NSDictionary *)setupWebAPHeaders:(NSString *)url{
    return [AGHTTPManagement shared].webAPHeaders;
}

+ (NSDictionary *)setupHMACHeaders:(NSString *)url{
    //# 客户名称
        NSString *customer_username = [AGHTTPManagement shared].customer_username;
    //# 客户密钥
        NSString *customer_secret = [AGHTTPManagement shared].customer_secret;
        
        NSURL *aburl = [NSURL URLWithString:[AGHTTPManagement shared].baseUrl];
        
        
        NSString *host = aburl.host;
        NSString *path = url;
        NSString *date = [self currentGMT];
        
        NSString *request_line = [NSString stringWithFormat:@"POST %@ HTTP/1.1",path];
        NSString *signing_string =  [NSString stringWithFormat:@"host: %@\ndate: %@\n%@",host, date, request_line];
        NSString *signature = [self hmac:signing_string withKey:customer_secret];
        //base64.b64encode(hmac.new(customer_secret.encode("utf-8"), signing_string.encode("utf-8"), sha256).digest())
        NSString * authorization = [NSString stringWithFormat:@"hmac username=\"%@\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"%@\"",customer_username,signature];
        //'hmac username="{}", algorithm="hmac-sha256", headers="host date request-line", signature="{}"'.format(
        //customer_username, signature.decode("utf-8"))
        NSDictionary *dic = @{ @"host": host,  @"date": date, @"authorization": authorization };
        return dic;
}

+ (NSDictionary *)setupHeadersBase:(NSString *)base Path:(NSString *)url request:(NSString *)mode{
    NSInteger type = [AGHTTPManagement shared].type;
    switch (type) {
        case 0:
            return @{};
            break;
        case 1:
            return [self setupWebAPHeaders:url];
            break;
        case 2:
            return [self setupHMACHeadersBase:base Path:url request:mode];
            break;
        default:
            return @{};
            break;
    }
}

+ (NSDictionary *)setupHMACHeadersBase:(NSString *)base Path:(NSString *)url request:(NSString *)mode{
    //# 客户名称
    NSString *customer_username = [AGHTTPManagement shared].customer_username;
    //# 客户密钥
    NSString *customer_secret = [AGHTTPManagement shared].customer_secret;
    
    NSURL *aburl = [NSURL URLWithString:base];
    NSString *host = aburl.host;
    NSString *path = url;
    NSString *date = [self currentGMT];
    
    NSString *request_line = [NSString stringWithFormat:@"%@ %@ HTTP/1.1",mode,path];
    NSString *signing_string =  [NSString stringWithFormat:@"host: %@\ndate: %@\n%@",host, date, request_line];
    NSString *signature = [self hmac:signing_string withKey:customer_secret];
    //base64.b64encode(hmac.new(customer_secret.encode("utf-8"), signing_string.encode("utf-8"), sha256).digest())
    NSString * authorization = [NSString stringWithFormat:@"hmac username=\"%@\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"%@\"",customer_username,signature];
    //'hmac username="{}", algorithm="hmac-sha256", headers="host date request-line", signature="{}"'.format(
    //customer_username, signature.decode("utf-8"))
    return @{ @"host": host,  @"date": date, @"authorization": authorization };
}


+ (NSString *)currentGMT {
    NSDate *date = [NSDate date];
    NSTimeZone *tzGMT = [NSTimeZone timeZoneWithName:@"GMT"];
    [NSTimeZone setDefaultTimeZone:tzGMT];
    NSDateFormatter *iosDateFormater=[[NSDateFormatter alloc]init];
    iosDateFormater.dateFormat=@"EEE, dd MMM yyyy HH:mm:ss 'GMT'";
    iosDateFormater.locale=[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    return [iosDateFormater stringFromDate:date];
}

+ (NSString *)hmac:(NSString *)plaintext withKey:(NSString *)key{
    const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [plaintext cStringUsingEncoding:NSASCIIStringEncoding];
    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];
//    const unsigned char *buffer = (const unsigned char *)[HMACData bytes];
//    NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2];
//    for (int i = 0; i < HMACData.length; ++i){
//        [HMAC appendFormat:@"%02x", buffer[i]];
//    }
    return [HMACData base64EncodedStringWithOptions:0];
}
@end
